package android.slc.user.ui.user.vmbox

import android.slc.adapter.LoadMoreDataFormat3
import android.slc.adapter.PageModel
import android.slc.appbase.api.slc.callback.SlcObserver
import android.slc.appbase.repository.remote.PageTransformUtils
import android.slc.appbase.ui.vd.wrapper.BaseListPageWrapper
import android.slc.appbase.ui.vd.wrapper.IBaseListPageWrapper
import android.slc.commonlibrary.util.compat.SlcCollectionUtils
import android.slc.extras.component.tree.ui.TreeListVmBox
import android.slc.extras.user.entity.UserInfo
import android.slc.extras.user.repository.remote.UserServiceRepository
import android.slc.user.R
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.ToastUtils

/**
 *
 * @Description:
 * @Author: sunlunchang
 * @CreateDate: 2021/12/06 下午 2:42
 *
 */
abstract class UserListVmBox : TreeListVmBox<UserInfo>(),
    IBaseListPageWrapper<UserInfo> {

    private val baseListPageWrapper: BaseListPageWrapper<UserInfo>

    init {
        baseListPageWrapper = object : BaseListPageWrapper<UserInfo>(this) {

            override fun onLoadMore() {
                this@UserListVmBox.onLoadMore()
            }
        }
    }

    override fun getDataListSlcObserver(): SlcObserver<PageModel<UserInfo>> {
        return baseListPageWrapper.dataListSlcObserver
    }

    override fun getLoadMoreDataFormat3(): LoadMoreDataFormat3 {
        return baseListPageWrapper.loadMoreDataFormat3
    }

    override fun refresh() {
        baseListPageWrapper.refresh()
    }

    override fun onSucceed(data: PageModel<UserInfo>) {
        this.loadMoreDataFormat3.formatSimple(dataList, data)
        dataListOf.notifyChange()
    }

    override fun onError(errorCode: Int, errorMessage: String?) {
        onFailed(errorCode, errorMessage)
        this.loadMoreDataFormat3.loadMoreFail()
    }

    final override fun loadMore() {
        super.loadMore()
    }

    override fun onLoadMore() {
        loadMoreTree()
    }

    private fun getTreeId(): Long {
        return try {
            mTreeId.toLong()
        } catch (e: NumberFormatException) {
            0
        }
    }

    override fun loadMoreTree() {
        when {
            getTreeId() != 0L -> {
                UserServiceRepository.page(getTreeId(), loadMoreDataFormat3.offset)
                    .to(bindToLifecycle())
                    .subscribe(dataListSlcObserver)
            }
            CollectionUtils.isNotEmpty(mLeafIdList) -> {
                UserServiceRepository.listByIds(SlcCollectionUtils.transformT2(mLeafIdList,
                    CollectionUtils.Transformer { return@Transformer it.toString() }))
                    .to(bindToLifecycle())
                    .subscribe(dataListSlcObserver)
            }
            else -> {
                dataListSlcObserver.onNext(PageTransformUtils.getPageModelResult())
                ToastUtils.showShort(R.string.user_label_user_info_not_found)
            }
        }
    }

}